import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';
import { NzNotificationService } from 'ng-zorro-antd';
import { IfStmt } from '@angular/compiler';
declare var layui: any;
declare var layer: any;
declare var $: any;

@Injectable({
  providedIn: 'root'
})
export class UtilService {

  constructor(private router: Router, private message: NzMessageService, private notification: NzNotificationService) { }

  /**
   * 新开模块选项卡
   * @param url 
   */
  goTo(url: string) {
    setTimeout(() => {
      $('button.ant-modal-close.ng-star-inserted').click();
      localStorage.setItem('urlThis', url);
      this.router.navigateByUrl(url);
    }, 50);
  }

  //模块操作状态
  isState = {}
  isCache = {}

  limits = [12, 20, 30, 50];
  //url   get分页列表
  limit = 12;
  height = 555;
  //data  json全部数据列表
  limit2 = 12;
  height2 = 560;
  //user  弹窗列表
  limit3 = 100;
  height3 = 400;
  //mignxi  主从明细列表
  limit4 = 100;
  height4 = 515;

  height5 = 572;//主从明细多字段

  //定时时间
  setTime1 = 50
  setTime2 = 200
  /**
   *表格操作按钮宽度
   */
  width1 = 50 //一个按钮定义宽度
  width2 = 75 //两个按钮定义宽度
  width3 = 100//三个按钮定义宽度

  /* 菜单下级是否显示（左侧菜单收缩时切换选项卡使用） */
  itemMenu = true;

  /**
   * 表格get异步分页对象
   * url  数据源
   * id 表格标识
   * field  表格字段集合
   * toolbar  表格工具栏
   * pageNum  自定义表格页码
   * toolbarData  表格工具栏选项
   */
  getTable(url, id, field, toolbar?, pageNum?, toolbarData?) {
    var bar: any = typeof (toolbar) == 'undefined' ? false : toolbar
    var page: any = typeof (pageNum) == 'undefined' ? true : { curr: pageNum, hash: 'page' }
    var toolbarData: any = typeof (toolbarData) == 'undefined' ? [] : ['print', {
      title: '数据导出'
      , layEvent: 'data_output'
      , icon: 'layui-icon-export'
    }, {
        title: '文件导入'
        , layEvent: 'file_input'
        , icon: 'layui-icon-file-b'
      }, { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
        title: '模板下载'
        , layEvent: 'template_download'
        , icon: 'layui-icon-download-circle'
      }]
    return {
      elem: id
      , height: this.height4
      , url: url
      , toolbar: bar
      , defaultToolbar: toolbarData
      , page: page
      , limit: this.limit
      , limits: this.limits
      , cellMinWidth: 130
      , cols: [field]
      , request: {
        pageName: 'page' //页码的参数名称，默认：page
        , limitName: 'size' //每页数据量的参数名，默认：limit
      }
      , parseData: function (res) { //res 即为原始返回的数据
        return {
          'code': res.code, //解析接口状态
          'msg': res.message, //解析提示文本
          'count': res.object.total, //解析数据长度
          'data': res.object.list, //解析数据列表
          'operStatus': res.object.operStatus //是否缓存
        }
      }
      , response: {
        statusCode: 200 //规定成功的状态码，默认：0
        , dataName: 'data' //规定数据列表的字段名称，默认：data
      }
    }
  }

  /**
   * 表格post非异步数据对象
   */
  postTable(data, id, field, page?, height?) {
    height = height == undefined ? this.height4 : height;
    page = page == undefined ? true : page;
    return {
      elem: id
      , height: height
      , data: data
      , page: page //开启分页
      , limit: this.limit4
      , limits: this.limits
      , cellMinWidth: 120
      , cols: [field]
    }
  }
  /**
   * 鼠标悬浮展示表格数据
   */
  tdTitle() {
    $('th').each(function (index, element) {
      $(element).attr('title', $(element).text());
    });
    $('td').each(function (index, element) {
      $(element).attr('title', $(element).text());
    });
  };


  //禁用字段提示颜色
  fieldFalseColor = 'red'
  //正常字段提示颜色
  fieldTrueColor = '#595959'

  //禁用选项卡颜色
  tabFalseColor = '#CCCCCC'
  //正常选项卡颜色
  tabTrueColor = '#545454'

  patrn = /\S/;// 不能为空
  lv = /^(0.\d+|0|1)$/;// 只能输入0-1之间的小数，最大是1，最小为0，且最多输入2位小数
  zheng = /[1-9]\d*/;// 正整数
  xiaoshu = /[1-9]\d*.\d*|0.\d*[1-9]\d*/;// 正浮点数
  // jiage=/[1-9]\d*|[1-9]\d*.\d*|0.\d*[1-9]\d*/;// 整数或小数
  jiage = /[0-9]\d*|[0-9]\d*.\d*|0.\d*[0-9]\d*/;// 整数或小数
  bili = /^([0-9]{1}|[0-9].\d{1,4})$/;//比例 匹配一位数字 或 0到9开头浮点数，小数点后面最少1位最多4位字符

  decNum = /^([0-9]{1,9}|[0-9]{1,9}.\d{0,9})$/;//比例 匹配数字 或 小数，小数点后面最少0位最多N位字符
  /**
   * 返回正则匹配数字或小数，小数点位数为动态传递
   */
  onDecimal(num) {
    const dec = '^([0-9]{1,9}|[0-9]{1,9}.[0-9]{0,' + num + '})$';
    return new RegExp(dec);
  }


  unitId_post(data, unidid) {//post组织筛选unitid转化
    return Object.assign({}, data, unidid);
  }

  table_select(field, field_list) {//表格下拉数据对比接口列表数据，返回正确值
    var data = '';
    if (typeof (field_list) != 'undefined') {
      for (var i = 0; i < field_list.length; i++) {
        if (field == field_list[i].optionValue) {
          data = field_list[i].optionName;
        }
      }
    }
    return data;
  }

  cskSave(data1, data2) {//穿梭框传递原数组和新数组对比---返回添加和删除对象
    var a1 = data1;//初始化数组
    var a2 = data2;//变化后数组
    var a3 = new Array();//存储相同值数组
    for (var i = 0; i < a1.length; i++) {//存储相同值
      for (var j = 0; j < a2.length; j++) {
        if (a1[i] == a2[j]) {
          a3.push(a1[i]);
        }
      }
    }
    for (var i = 0; i < a3.length; i++) {//删除值 初始化数组减去相同值数组
      for (var j = 0; j < a1.length; j++) {
        if (a3[i] == a1[j]) {
          a1.splice(j, 1);
        }
      }
    }
    for (var i = 0; i < a3.length; i++) {//增加值 初始化数组减去相同值数组
      for (var j = 0; j < a2.length; j++) {
        if (a3[i] == a2[j]) {
          a2.splice(j, 1);
        }
      }
    }

    var data = {
      data1: a2,
      data2: a1
    }
    return data;
  }

  filed_hide(filed_clos, fieldFull) {//表格隐藏字段---传递初始化表格对象filed_clos和需要隐藏字段fieldFull，处理后返回隐藏好的新表格对象
    if (fieldFull.length > 0) {
      for (var i = 0; i < fieldFull.length; i++) {
        for (var ii = 0; ii < filed_clos.length; ii++) {
          if (fieldFull[i]['tableFiled'] == filed_clos[ii]['field']) {
            filed_clos[ii]['hide'] = true;
          }
        }
      }
    }
    return filed_clos;
  }

  filed_hide2(filed_clos, fieldFull) {//表格隐藏字段格式2（下拉格式）---传递初始化表格对象filed_clos和需要隐藏字段fieldFull，处理后返回隐藏好的新表格对象
    if (fieldFull.length > 0) {
      for (var i = 0; i < fieldFull.length; i++) {
        for (var ii = 0; ii < filed_clos.length; ii++) {
          if (fieldFull[i]['optionValue'] == filed_clos[ii]['field']) {
            filed_clos[ii]['hide'] = true;
          }
        }
      }
    }
    return filed_clos;
  }


  filedlist = []
  /**
   * 表格字段动态列组合主表-无操作（修改删除）
   * @param fieldFull   表格列集合
   * @param checkbox    可选参数，传1为多选表格
   */
  filed_list(fieldFull, checkbox?) {
    this.filedlist = []
    if (fieldFull.length > 0) {
      if (checkbox == 1) {
        this.filedlist.push({ type: 'checkbox', fixed: 'left' })
      } else {
        this.filedlist.push({ title: '序号', type: 'numbers', fixed: 'left' })
      }
      for (var i = 0; i < fieldFull.length; i++) {
        if (fieldFull[i]['style']) {
          var list = { field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] };
          var pdata = fieldFull[i]['style'];
          var style = '';
          for (let o in pdata) {
            if (o === 'width') {
              list[o] = pdata[o] == null ? 0 : pdata[o];
            } else if (o === 'font-size') {
              style = style + o + ':' + pdata[o] + 'px;';
            } else {
              style = style + o + ':' + pdata[o] + ';';
            }
          }
          list['style'] = style;
          this.filedlist.push(list)
        } else {
          this.filedlist.push({ field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] })
        }
      }
    }
    return this.filedlist;
  }
  filed_list1(fieldFull, width?) {//表格字段动态列组合主表-带操作（修改删除）
    this.filedlist = []
    if (fieldFull.length > 0) {
      this.filedlist.push({ title: '序号', type: 'numbers', fixed: 'left' })
      for (var i = 0; i < fieldFull.length; i++) {
        if (fieldFull[i]['style']) {
          var list = { field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] };
          var pdata = fieldFull[i]['style'];
          var style = '';
          for (let o in pdata) {
            if (o === 'width') {
              list[o] = pdata[o] == null ? 0 : pdata[o];
            } else if (o === 'font-size') {
              style = style + o + ':' + pdata[o] + 'px;';
            } else {
              style = style + o + ':' + pdata[o] + ';';
            }
          }
          list['style'] = style;
          this.filedlist.push(list)
        } else {
          this.filedlist.push({ field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] })
        }
      }
      this.filedlist.push({ fixed: 'right', title: '操作', toolbar: '#barDemo', width: typeof (width) == 'undefined' ? 80 : width })
    }
    return this.filedlist;
  }
  /**
   * 表格字段动态列组合子表-添加修改删除操作  
   * @param fieldFull 字段集合
   * @param add       第二参数可选，传递为添加按钮id（多子表避免id冲突使用）
   * @param bar       第三参数可选，传递为添加操作id（多子表操作不一样时使用：如表二修改删除，表三无修改只能删除）
   */
  filed_list2(fieldFull, add?, bar?, width?) {//
    if (typeof (add) == 'undefined') {
      add = 'add2'
    }
    if (typeof (bar) == 'undefined') {
      bar = 'barDemo2'
    }
    this.filedlist = []
    var addButton = '<button class=\'layui-btn layui-btn-xs layui-btn-danger\' style=\'height:20px;line-height:20px;\' id=' + add + '>添加</button>';
    if (fieldFull.length > 0) {
      this.filedlist.push({ title: addButton, type: 'numbers' })
      for (var i = 0; i < fieldFull.length; i++) {
        if (fieldFull[i]['style']) {
          var list = { field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] };
          var pdata = fieldFull[i]['style'];
          var style = '';
          for (let o in pdata) {
            if (o === 'width') {
              list[o] = pdata[o] == null ? 0 : pdata[o];
            } else if (o === 'font-size') {
              style = style + o + ':' + pdata[o] + 'px;';
            } else {
              style = style + o + ':' + pdata[o] + ';';
            }
          }
          list['style'] = style;
          this.filedlist.push(list)
        } else {
          this.filedlist.push({ field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] })
        }
      }
      this.filedlist.push({ fixed: 'right', title: '操作', toolbar: '#' + bar, width: typeof (width) == 'undefined' ? 80 : width })
    }
    return this.filedlist;
  }

  /**
   * 表格字段动态列组合子表-修改删除操作  --无明细添加按钮
   * @param fieldFull 字段集合
   * @param add       第二参数可选，传递为添加按钮id（多子表避免id冲突使用）
   * @param bar       第三参数可选，传递为添加操作id（多子表操作不一样时使用：如表二修改删除，表三无修改只能删除）
   */
  filed_list3(fieldFull, bar?, width?) {//
    if (typeof (bar) == 'undefined') {
      bar = 'barDemo2'
    }
    this.filedlist = []
    if (fieldFull.length > 0) {
      this.filedlist.push({ title: '序号', type: 'numbers', fixed: 'left' })
      for (var i = 0; i < fieldFull.length; i++) {
        if (fieldFull[i]['style']) {
          var list = {};
          if (fieldFull[i]['edit']) {
            list = { field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'], edit: 'text' };
          } else {
            list = { field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] };
          }

          var pdata = fieldFull[i]['style'];
          var style = '';
          for (let o in pdata) {
            if (o === 'width') {
              list[o] = pdata[o] == null ? 0 : pdata[o];
            } else if (o === 'font-size') {
              style = style + o + ':' + pdata[o] + 'px;';
            } else {
              style = style + o + ':' + pdata[o] + ';';
            }
          }
          list['style'] = style;
          this.filedlist.push(list)
        } else {
          if (fieldFull[i]['edit']) {
            this.filedlist.push({ field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'], edit: 'text' })
          } else {
            this.filedlist.push({ field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] })
          }
        }
      }
      this.filedlist.push({ fixed: 'right', title: '操作', toolbar: '#' + bar, width: typeof (width) == 'undefined' ? 80 : width })
    }
    return this.filedlist;
  }

  /**
   * 表格字段动态列组合子表-无操作，只能查看
   * @param fieldFull 字段集合
   */
  filed_list4(fieldFull, checkbox?) {
    this.filedlist = []
    if (fieldFull.length > 0) {
      if (typeof (checkbox) == 'undefined') {
        this.filedlist.push({ title: '序号', type: 'numbers', fixed: 'left' })
      } else {
        this.filedlist.push({ type: 'checkbox', fixed: 'left' })
      }
      for (var i = 0; i < fieldFull.length; i++) {
        this.filedlist.push({ field: fieldFull[i]['fieldValue'], title: fieldFull[i]['fieldName'], hide: fieldFull[i]['hideField'] })
      }
    }
    return this.filedlist;
  }

  /**
   * 采购审批设置专用--修改添加 
   * @param fieldFull 
   */
  filed_list5(fieldFull) {//表格字段动态列组合主表-带操作（修改删除）
    this.filedlist = []
    if (fieldFull.length > 0) {
      // this.filedlist.push({title: '序号', type: 'numbers',fixed: 'left'})
      this.filedlist.push({ title: '层级', field: 'approvalLevel', fixed: 'left' })
      for (var i = 0; i < fieldFull.length; i++) {
        this.filedlist.push({ field: fieldFull[i]["fieldValue"], title: fieldFull[i]["fieldName"], hide: fieldFull[i]["hideField"] })
      }
      this.filedlist.push({ fixed: 'right', title: '操作', toolbar: this.bar, width: 100 })
    }
    return this.filedlist;
  }

  bar = '<div>\
  <a class=\"layui-btn layui-btn-xs layui-btn-danger barDemo_edit1\" title=\"添加子级\" lay-event=\"add\" style=\"float:left;height:20px;line-height:20px;\"><i class=\"layui-icon\"></i></a>\
  <a class=\"layui-btn layui-btn-xs barDemo_edit2\" title=\"修改\" lay-event=\"edit\" style=\"float:left;height:20px;line-height:20px;\"><i class=\"layui-icon\">&#xe642;</i></a>\
  <a class=\"layui-btn layui-btn-danger layui-btn-xs barDemo_edit2\" title=\"删除\" lay-event=\"del\" style=\"float:left;height:20px;line-height:20px;\"><i class=\"layui-icon\">&#xe640;</i></a>\
  </div>'

  /**
   * 根据动态列返回下拉框默认赋值集合
   * @param data 
   */
  selectDefaultValue(data, fieldName?, fieldValue?) {
    const selectValue = {}
    if (data.length > 0) {
      for (var i = 0; i < data.length; i++) {
        if (fieldName) {
          selectValue[data[i][fieldName]] = data[i][fieldValue]
        } else {
          selectValue[data[i]['fieldValue']] = data[i]['defaultValue']
        }
      }
    }
    return selectValue;
  }

  /**
   * 根据动态列返回下拉框默认集合，结合下拉集合实际数据匹配，修改最新下拉默认值
   * @param name 原下拉字段动态列所返回字段名称
   * @param value 原下拉字段动态列所返回默认值
   * @param data  原下拉字段集合数据
   */
  selectEditValue(name, value, data, optionValue?) {
    var onValue = 'optionValue';
    if (optionValue) {
      onValue = optionValue;
    }
    var selectValue = ''
    if (value === '' || value === null) {
      if (data.length > 0) {
        selectValue = data[0][onValue]
      }
    } else {
      for (var i = 0; i < data.length; i++) {
        if (value === data[i][onValue]) {
          selectValue = value
        }
      }
    }
    return selectValue;
  }

  /**
   * 根据动态列返回下拉框默认集合，结合下拉集合实际数据匹配，修改最新下拉默认值
   * @param name 原下拉字段动态列所返回字段名称
   * @param value 原下拉字段动态列所返回默认值
   * @param data  原下拉字段集合数据
   */
  value1
  selectEditName(name, value, data, optionName?) {
    var onName = 'optionName';
    if (optionName) {
      onName = optionName;
    }
    var selectName = ''
    if (value === '' || value === null) {
      if (data.length > 0) {
        selectName = data[0][onName]
      }
    } else {
      if (value != undefined) {
        this.value1 = data.find(item => item.optionValue == value)
      }
      for (var i = 0; i < data.length; i++) {
        if (this.value1 != undefined) {
          if (this.value1[onName] === data[i][onName]) {
            selectName = this.value1[onName]
          }
        }
      }
    }
    return selectName;
  }

  /**
   * 返回缓存中当前url对应参数对象
   * @param urlKey 现访问url标识
   * @param urlData 原url跳转数组
   */
  urlParm(urlKey, urlData) {
    var fldMapping = {};
    for (var i = 0; i < urlData.length; i++) {
      if (urlKey === urlData[i]['selectData']) {
        fldMapping = urlData[i]['parm']
      }
    }
    return fldMapping;
  }

  /**
   * 返回缓存中待跳转下一条url
   * @param urlKey 现访问url标识
   * @param urlData 原url跳转数组
   */
  urlNext(urlKey, urlData) {
    var nextUrl = '';
    for (var i = 0; i < urlData.length; i++) {
      if (urlKey === urlData[i]['selectData'] && i < urlData.length - 1) {
        nextUrl = urlData[i + 1]['jumpUrl']
      }
    }
    return nextUrl;
  }


  /**
   * 比较2个对象是否相同
   */
  isObjEqual(o1, o2) {
    delete o1.LAY_TABLE_INDEX;
    delete o2.LAY_TABLE_INDEX;
    var props1 = Object.getOwnPropertyNames(o1);
    var props2 = Object.getOwnPropertyNames(o2);
    if (props1.length != props2.length) {
      return false;
    }
    for (var i = 0, max = props1.length; i < max; i++) {
      var propName = props1[i];
      if (o1[propName] !== o2[propName]) {
        return false;
      }
    }
    return true;
  }

  /**
   * 全局提示
   */
  msg(message) {
    // this.message.success(message, { nzDuration: 10000 });
    this.notification.config({
      nzPlacement: 'bottomRight',
      nzDuration: 300000
    });
    this.notification.blank('查看报表提示', ' "' + message + '" 模块正在编辑中，请处理完后再进行报表操作！');
  }

  /**
   * 判断已有权限列表中，被查询权限是否存在
   * @param name 被查询权限名称
   */
  isPrivi(name) {
    let flag = false;
    const privAll = JSON.parse(localStorage.getItem('priviAll'));
    if (privAll) {
      for (let i = 0; i < privAll.length; i++) {
        if (privAll[i]['privId'] === name) {
          flag = true;
          break;
        }
      }
    }
    return flag;
  }

  /**
   * 表格点击行切换多选状态
   */
  checkboxClick(componentName, tableid) {
    // $(document).off('click');
    $(componentName).off('click', 'div[lay-id=' + tableid + '] table.layui-table tbody tr');
    $(componentName).on('click', 'div[lay-id=' + tableid + '] table.layui-table tbody tr', function () {
      var index = $(this).attr('data-index');
      var tableBox = $(this).parents('.layui-table-box');
      //存在固定列
      if (tableBox.find('.layui-table-fixed.layui-table-fixed-l').length > 0) {
        var tableDiv = tableBox.find('.layui-table-fixed.layui-table-fixed-l');
      } else {
        var tableDiv = tableBox.find('div[lay-id=' + tableid + '] .layui-table-main');
      }
      var checkCell = tableDiv.find('tr[data-index=' + index + ']').find('td div.laytable-cell-checkbox div.layui-form-checkbox I');
      if (checkCell.length > 0) {
        checkCell.click();
      }
      //选中背景色
      $(this).siblings().css('background-color', '#FFFFFF');
      $(this).css('background-color', '#F2F2F2');
    });

    $(componentName).on('click', 'div[lay-id=' + tableid + '] td div.laytable-cell-checkbox div.layui-form-checkbox', function (e) {
      e.stopPropagation();
    });
  }


}
